<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Source extends MY_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model('DemandGroup');
        $this->load->model('TopicUnit');
        $this->load->model('TopicDetection');
        $this->load->model('AnswerType');
        $this->load->model('TopicAnswer');
        $this->load->model('TopicQuestionType');
    }

    public function index()
    {
        $this->load->view('source/index');
    }

    public function showList()
    {
        $result = $this->TopicUnit->find(array(
            'parents' => 'ROOT',
            'is_valid' => TRUE
        ));
        $questionTypes = $this->TopicQuestionType->find(array('is_valid'=>true));
        $questionTypeArr = array();
        foreach ($questionTypes as $questionType){
            $questionTypeArr[$questionType['question_type']] = $questionType['name'];
        }
        foreach ($result as $value) {
            $value['_id'] = $value['_id'];
            $demand = $this->DemandGroup->findOne(array(
                'demander' => $value['source'],
                'is_valid' => TRUE
            ));
            $value['business'] = $demand['content_group']?$demand['content_group']:array();
            $answerType = $this->AnswerType->findOne(array('topic_id'=>$value['_id']));
            $value['answerType'] = $questionTypeArr[$answerType['answer_type']];
            $unit[] = $value;
        }
        
        $data['sources'] = $unit;
        $this->load->view('source/sourceList', $data);
    }

    
    
    
    function editSource($id)
    {
        $unit = $this->TopicUnit->findOne(array('_id' => new MongoId($id)), array());
        $demand = $this->DemandGroup->findOne(array(
            'demander' => $unit['source'],
        ));
        $answerType = $this->AnswerType->findOne(array('topic_id'=>$id));
        $unit['business'] = $demand['content_group']?$demand['content_group']:array();
        $sources = $this->TopicUnit->find(array('parents' => 'ROOT', 'is_valid' => TRUE), array('source'));
        foreach ($sources as $k=>$v){
            if(!empty($v['source'])){
                $result[] = $v['source'];
            }
        }
        $result = array_diff($result, array($unit['source']));
        $result = array_merge($result);
        $data['source'] = $unit;
        $data['showSource'] = $result;
        $data['answerType'] = $answerType['answer_type'];
        $data['questionTypes'] = $this->TopicQuestionType->find(array('is_valid'=>true),array('question_type','name'));
        $this->load->view('source/editSource', $data);
    }
    
    
    function checkSource()
    {
        $id = $_REQUEST['id'];
        $source = $_REQUEST['source'];
        $oldTopicUnit = $this->TopicUnit->findOne(array(
            '_id' => new MongoId($id)
        ));
        // source字段不能重复
        if ($oldTopicUnit['source'] != $source) {
            $res = $this->TopicUnit->getCount(array(
                'source' => $source
            ));
            if ($res > 0) {
                $data['code'] = 0;
                $data['msg'] = '已存在渠道' . $source;
                
            }else{
                $data['code'] = 1;
                $data['msg'] = '不存在渠道'.$source;
            }
        }else{
            $data['code'] = 1;
            $data['msg'] = '渠道，没有修改';
        }
        echo json_encode($data);
        
    }
    
    // 保存编辑的source
    function saveEditSource($id)
    {
        $operator = $_SESSION['user']['username'];
        $business = empty($_REQUEST['business'])?array():$_REQUEST['business'];
        $source = trim($_REQUEST['source']);
        $answerType = trim($_REQUEST['answerType']);
        $oldTopicUnit = $this->TopicUnit->findOne(array(
            '_id' => new MongoId($id)
        ));
        array_unshift($business, $oldTopicUnit['source']);
        // source字段不能重复
        if ($oldTopicUnit['source'] != $source) {
            $res = $this->TopicUnit->getCount(array(
                'source' => $source
            ));
            if ($res > 0) {
                $data['code'] = 0;
                $data['msg'] = '已存在渠道' . $source;
                echo json_encode($data);
                return false;
            }
        }
        $result1 = $result2 = $result3 = $result4 = $result5 = $result6 = true;
        // 添加demand_group表
        $oldDemandGroup = $this->DemandGroup->findOne(array(
            'demander' => $oldTopicUnit['source']
        ));
        // 判断demand_group表中记录是否存在
        if ($oldDemandGroup) {
            if ($oldDemandGroup['content_group'] != $business) {
                $query = array(
                    'demander' => $oldTopicUnit['source']
                );
                $updateData = array(
                    'content_group' => $business,
                    "update_time" => date("Y-m-d H:i:s", time()),
                    "operator" => $operator
                );
                $result6 = $this->DemandGroup->update($query, $updateData);
            }
        } else {
            $insertData = array(
                "demander" => $oldTopicUnit['source'],
                "content_group" => $business,
                "update_time" => date("Y-m-d H:i:s", time()),
                "is_valid" => true,
                "operator" => $operator
            );
            $result6 = $this->DemandGroup->insert($insertData);
        }
        // 判断answer_type表中记录是否存在
        $oldAnswerType = $this->AnswerType->findOne(array(
            'topic_id' => $id
        ));
        if ($oldAnswerType) {
            if ($oldAnswerType['answer_type'] != $answerType) {
                $query = array(
                    'topic_id' => $id
                );
                $updateData = array(
                    'answer_type' => $answerType,
                    "update_time" => date("Y-m-d H:i:s", time()),
                    "operator" => $operator
                );
                $result6 = $this->AnswerType->update($query, $updateData);
                //将该ROOT节点下面所有的answer的answer_type进行修改
                $childers = $this->findChilds($id);
                foreach($childers as $childer){
                    $childeranswers = $this->TopicAnswer->find(array('answer_type'=>$oldAnswerType['answer_type'],'topic_id'=>$childer['_id']));
                    if($childeranswers){
                        foreach ($childeranswers as $childeranswer){
                            $this->TopicAnswer->update(array('_id'=>new MongoId($childeranswer['_id'])),array('answer_type'=>$answerType));
                        }
                    }
                }
            }
        } else {
            $insertData = array(
                'topic_id'=> $id,
                'answer_type'=>$answerType,
                'update_time'=> date("Y-m-d H:i:s", time()),
                "is_valid" => true,
                'operator'=> $operator
            );
            $result6 = $this->AnswerType->insert($insertData);
        }
        // 修改表中的source字段
        if ($oldTopicUnit['source'] != $source) {
            $update = array(
                'source' => $source
            );
            $result1 = $this->TopicUnit->update(array('source' => $oldTopicUnit['source']), $update, array('multiple'=>true));
            $result2 = $this->TopicDetection->update(array('source' => $oldTopicUnit['source']), $update, array('multiple'=>true));
            // 修改demandGroup表
            $demands = $this->DemandGroup->find(array(
                "content_group" => array(
                    '$in' => array(
                        $oldTopicUnit['source']
                    )
                )
            ));
            foreach ($demands as $demand) {
                $newContent = array();
                foreach ($demand['content_group'] as $k => $v) {
                    if ($v == $oldTopicUnit['source']) {
                        $newContent[] = $source;
                    } else {
                        $newContent[] = $v;
                    }
                }
                // 修改content_group字段
                $result4 = $this->DemandGroup->update(array(
                    '_id' => new MongoId($demand['_id'])
                ), array(
                    'content_group' => $newContent,
                    "update_time" => date("Y-m-d H:i:s", time()),
                    "operator" => $operator
                ));
            }
            // 修改demand字段
            $result5 = $this->DemandGroup->update(array(
                'demander' => $oldTopicUnit['source']
            ), array(
                'demander' => $source,
                "update_time" => date("Y-m-d H:i:s", time()),
                "operator" => $operator
            ));
        }
        
        if ($result1 && $result2 && $result3 && $result4 && $result5) {
            $data['code'] = 1;
            $data['msg'] = '修改成功';
        } else {
            $data['code'] = 0;
            $data['msg'] = '修改失败';
        }
        $this->load->view('source/editSource', $data);
    }
    
    //初始化渠道    
    function initSource($id)
    {
        $operator = $_SESSION['user']['username'];
        $business = empty($_REQUEST['business'])?array():$_REQUEST['business'];
        $source = trim($_REQUEST['source']);
        $answerType = trim($_REQUEST['answerType']);
        array_unshift($business, $source);
        // source字段不能重复
        $res = $this->TopicUnit->getCount(array(
            'source' => $source
        ));
        if ($res > 0) {
            $data['code'] = 0;
            $data['msg'] = '已存在渠道' . $source;
            echo json_encode($data);
            return false;
        }
        
        $result1 = $result2 = $result3 = $result4 = $result5 = true;
            $childs = $this->findChilds($id);
            $update = array(
                'source' => $source
            );
            //初始化子节点
            if ($childs) {
                foreach ($childs as $value) {
                    $result1 = $this->TopicDetection->update(array(
                        'topic_id' => $value['_id']
                    ), $update);
                    $result2 = $this->TopicUnit->update(array(
                        '_id' => new MongoId($value['_id'])
                    ), $update);
                }
            }
            //初始化自己
            $result3 = $this->TopicUnit->update(array(
                '_id' => new MongoId($id)
            ), $update);
            //初始化demand_group
            $insertData = array(
                "demander" => $source,
                "content_group" => $business,
                "update_time" => date("Y-m-d H:i:s", time()),
                "is_valid" => true,
                "operator" => $operator
            );
            $result4 = $this->DemandGroup->insert($insertData);
            //初始化answer_type表
            $insertAnswerType = array(
                'topic_id'=> $id,
                'answer_type'=>$answerType,
                'update_time'=> date("Y-m-d H:i:s", time()),
                "is_valid" => true,
                'operator'=> $operator ,
            );
            $result5 = $this->AnswerType->insert($insertAnswerType);
        if ($result1 && $result2 && $result3 && $result4 && $result5) {
            $data['code'] = 1;
            $data['msg'] = '修改成功';
        } else {
            $data['code'] = 0;
            $data['msg'] = '修改失败';
        }
        $this->load->view('source/editSource', $data);
    }

    function findChilds($id)
    {
        static $childTemp;
        $result = $this->TopicUnit->find(array(
            'parents' => $id
        ));
        foreach ($result as $value) {
            $childTemp[] = $value;
            $this->findChilds($value['_id']);
        }
        return $childTemp;
    }
}
